<template>
  <div class="repassword-page">
    <van-nav-bar 
      title="重置密码" 
      left-arrow 
      @click-left="onBack" 
      fixed 
      placeholder
      :border="false"
      :safe-area-inset-top="true"
    />
    <div v-if="step === 1" class="card">
      <div class="title">重置密码 <span>🔑</span></div>
      <div class="desc">请输入您的电子邮箱，我们将在下一步发送验证码以便重置您的密码。</div>
      <van-field v-model="email" label="邮箱" placeholder="请输入注册邮箱" clearable :disabled="!!userEmail" />
      <van-button block type="primary" class="main-btn" @click="sendCode">立即发送</van-button>
    </div>
    <div v-else-if="step === 2" class="card">
      <div class="title">输入验证码 <span>🔒</span></div>
      <div class="desc">我们已向注册邮箱 <span class="email-mask">{{ emailMask }}</span> 发送验证码，请在下方输入验证码进行验证。</div>
      <div class="code-inputs">
        <input v-for="(v, i) in 4" :key="i" maxlength="1" class="code-box" v-model="codeArr[i]" @input="onCodeInput(i, $event)" />
      </div>
      <div class="code-tip">
        <span v-if="countdown > 0">你可以在 {{ countdown }}s 后重新发送</span>
        <span v-else class="resend" @click="sendCode">重新发送</span>
      </div>
      <van-number-keyboard v-model="currentInput" :show="showKeyboard" @blur="showKeyboard=false" />
    </div>
    <div v-else-if="step === 3" class="card">
      <div class="title">创建新密码 <span>🔒</span></div>
      <div class="desc">创建更安全的新密码。如果您忘记了密码，则需要执行云忘记密码操作。</div>
      <van-field 
        v-model="newPwd" 
        label="新密码" 
        placeholder="请输入新密码" 
        :type="showPwd ? 'text' : 'password'" 
        clearable 
        :right-icon="showPwd ? 'eye-o' : 'closed-eye'" 
        @click-right-icon="showPwd = !showPwd" 
      />
      <van-field 
        v-model="confirmPwd" 
        label="确认新密码" 
        placeholder="请再次输入新密码" 
        :type="showConfirmPwd ? 'text' : 'password'" 
        clearable 
        :right-icon="showConfirmPwd ? 'eye-o' : 'closed-eye'" 
        @click-right-icon="showConfirmPwd = !showConfirmPwd" 
      />
      <van-button block type="primary" class="main-btn" @click="resetPwd">立即创建</van-button>
    </div>
    <van-dialog v-model:show="showDialog" :show-cancel-button="false" :close-on-click-overlay="false" title="重置密码成功！">
      <div style="text-align:center;padding:16px 0;">
        <van-icon name="passed" size="48" color="#a48fff" style="margin-bottom:8px;" />
        <div style="font-size:16px;color:#7c5dfa;">请稍候...<br>您即将跳转至主页。</div>
        <van-loading color="#a48fff" size="32" style="margin-top:12px;" />
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { db, STORES } from '../../utils/db'

const router = useRouter()
const step = ref(1)
const email = ref(localStorage.getItem('userEmail') || '')
const userEmail = localStorage.getItem('userEmail')
const code = ref('')
const codeArr = ref(['', '', '', ''])
const currentInput = ref('')
const showKeyboard = ref(false)
const countdown = ref(60)
const timer = ref(null)
const newPwd = ref('')
const confirmPwd = ref('')
const showPwd = ref(false)
const showConfirmPwd = ref(false)
const showDialog = ref(false)

const emailMask = computed(() => {
  if (!email.value) return ''
  const e = email.value
  return e.length > 6 ? e.slice(0, 2) + '****' + e.slice(-6) : e
})

function onBack() {
  router.back()
}

async function sendCode() {
  if (!email.value) {
    showToast('请输入邮箱')
    return
  }
  
  try {
    // 从 IndexedDB 获取用户列表
    const userList = await db.getAll(STORES.USER_LIST)
    const user = userList.find(u => u.account === email.value)
    
    if (!user) {
      showToast('该账号未注册')
      return
    }
    
    // 生成验证码（本地模拟）
    code.value = Math.floor(1000 + Math.random() * 9000).toString()
    showToast('验证码已发送（模拟：' + code.value + '）')
    step.value = 2
    codeArr.value = ['', '', '', '']
    countdown.value = 60
    clearInterval(timer.value)
    timer.value = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) clearInterval(timer.value)
    }, 1000)
  } catch (error) {
    console.error('验证账号失败:', error)
    showToast('验证失败，请重试')
  }
}

function onCodeInput(i, e) {
  const val = e.target.value.replace(/[^0-9]/g, '')
  codeArr.value[i] = val
  if (val && i < 3) {
    // 自动跳到下一个输入框
    const next = document.querySelectorAll('.code-box')[i + 1]
    if (next) next.focus()
  }
  if (codeArr.value.join('').length === 4) {
    verifyCode()
  }
}

function verifyCode() {
  if (codeArr.value.join('') === code.value) {
    step.value = 3
  } else {
    showToast('验证码错误')
    codeArr.value = ['', '', '', '']
  }
}

async function resetPwd() {
  if (!newPwd.value || !confirmPwd.value) {
    showToast('请填写完整新密码')
    return
  }
  if (newPwd.value !== confirmPwd.value) {
    showToast('两次密码不一致')
    return
  }
  
  try {
    // 从 IndexedDB 获取用户
    const user = await db.get(STORES.USER_LIST, email.value)
    if (!user) {
      showToast('用户不存在')
      return
    }
    
    // 更新用户密码
    user.password = newPwd.value
    await db.put(STORES.USER_LIST, user)
    
    // 如果当前登录的是该用户，更新本地存储的密码
    if (userEmail === email.value) {
      localStorage.setItem('userPwd', newPwd.value)
    }
    
    showDialog.value = true
    setTimeout(() => {
      showDialog.value = false
      // 清除登录状态，强制重新登录
      localStorage.removeItem('isLogin')
      localStorage.removeItem('userPwd')
      router.replace('/login')
    }, 1800)
  } catch (error) {
    console.error('重置密码失败:', error)
    showToast('重置失败，请重试')
  }
}
</script>

<style scoped>
.repassword-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f6ff 0%, #e9eafc 100%);
  padding-bottom: 16px;
}

.van-nav-bar {
  background: #fff !important;
}

.van-nav-bar :deep(.van-nav-bar__title) {
  color: #333;
  font-size: 17px;
  font-weight: 600;
}

.van-nav-bar :deep(.van-icon) {
  color: #333;
}

.card {
  background: #fff;
  border-radius: 24px;
  margin: 32px 16px 0 16px;
  padding: 32px 18px 18px 18px;
  box-shadow: 0 2px 16px #ece8ff44;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.title {
  font-size: 22px;
  font-weight: bold;
  color: #222;
  margin-bottom: 8px;
  width: 100%;
  text-align: left;
}
.desc {
  font-size: 14px;
  color: #888;
  margin-bottom: 24px;
  width: 100%;
  text-align: left;
}
.email-mask {
  color: #7c5dfa;
  font-weight: 500;
}
.code-inputs {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin: 24px 0 12px 0;
}
.code-box {
  width: 44px;
  height: 44px;
  border-radius: 12px;
  border: 2px solid #a48fff;
  background: #f8f6ff;
  text-align: center;
  font-size: 22px;
  color: #7c5dfa;
  outline: none;
  transition: border 0.2s;
}
.code-box:focus {
  border: 2px solid #7c5dfa;
  background: #f3edff;
}
.code-tip {
  font-size: 13px;
  color: #aaa;
  margin-bottom: 8px;
}
.resend {
  color: #7c5dfa;
  cursor: pointer;
}
.main-btn {
  background: #a48fff;
  border-radius: 18px;
  margin-top: 18px;
  font-size: 16px;
  font-weight: bold;
  height: 48px;
}
</style>
